package me.zxk.smartagriculture.repository;

import me.zxk.smartagriculture.entity.Comment;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.Optional;

/**
 * 评论数据访问层
 */
@Repository
public interface CommentRepository extends JpaRepository<Comment, Long> {

    /**
     * 根据新闻ID分页查询正常状态的评论
     */
    Page<Comment> findByNewsIdAndStatus(Long newsId, Integer status, Pageable pageable);

    /**
     * 根据用户ID分页查询评论
     */
    Page<Comment> findByUserId(Long userId, Pageable pageable);

    /**
     * 根据ID和用户ID查询评论
     */
    Optional<Comment> findByIdAndUserId(Long id, Long userId);

    /**
     * 统计新闻的评论数量
     */
    long countByNewsIdAndStatus(Long newsId, Integer status);

    /**
     * 统计用户的评论数量
     */
    long countByUserId(Long userId);

    /**
     * 增加评论点赞数
     */
    @Modifying
    @Query("UPDATE Comment c SET c.likeCount = c.likeCount + 1 WHERE c.id = :id")
    void incrementLikeCount(@Param("id") Long id);

    /**
     * 减少评论点赞数
     */
    @Modifying
    @Query("UPDATE Comment c SET c.likeCount = c.likeCount - 1 WHERE c.id = :id AND c.likeCount > 0")
    void decrementLikeCount(@Param("id") Long id);

    /**
     * 软删除评论（设置状态为0）
     */
    @Modifying
    @Query("UPDATE Comment c SET c.status = 0 WHERE c.id = :id AND c.userId = :userId")
    void softDeleteByIdAndUserId(@Param("id") Long id, @Param("userId") Long userId);
}
